﻿using System;
using System.Collections.Generic;
using System.Net.Sockets;
namespace GX
{
    public class NetSender
    {
        private readonly System.Object _locker = new object();
        private NetManager _netMgr;
        private Socket _sock;
        private byte[] _buffer = new byte[NetConfig.BUFFER_SIZE];

        public void Setup(NetManager netMgr, Socket sock)
        {
            _netMgr = netMgr;
            _sock = sock;
        }
        public void Send(IPackageOut pkg)
        {
            lock (_locker)
            {
                if (null == _sock)
                {
                    return;
                }
                if (null == _sock
                    || false == _sock.Connected)
                {
                    return;
                }
                bool isOk = true;
                try
                {
                    DoSend(pkg);
                }
                catch (Exception e)
                {
                    isOk = false;
                    if (null != _netMgr)
                    {
                        if (null != _netMgr && null != _netMgr.onError)//本地网络有问题
                        {
                            _netMgr.onError(_netMgr, e.Message);
                        }
                    }
                }
                finally
                {
                    if (isOk)
                    {

                    }
                }
            }

        }
        private void DoSend(IPackageOut pkg)
        {
            PackageOut pkgOut = pkg as PackageOut;
            if (null == pkgOut) return;




            int writeOffset = 0;

            int numDataLeft = pkgOut.length - writeOffset;

            pkgOut.BeforeSendOut();

            while (numDataLeft > 0)
            {
                int numCanWrite = Math.Min(NetConfig.BUFFER_SIZE, numDataLeft);

                Buffer.BlockCopy(pkgOut.buffer, writeOffset, _buffer, 0, numCanWrite);

                _sock.Send(_buffer, 0, numCanWrite, SocketFlags.None);

                writeOffset += numCanWrite;
                numDataLeft -= writeOffset;

            }
            Array.Clear(_buffer, 0, NetConfig.BUFFER_SIZE);
        }
    }//END CLASS
}